package com.example.mallsystem1104.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.mallsystem1104.annotation.Authority;
import com.example.mallsystem1104.common.Result;
import com.example.mallsystem1104.constants.Constants;
import com.example.mallsystem1104.entity.AuthorityType;
import com.example.mallsystem1104.entity.MyFile;
import com.example.mallsystem1104.exception.ServiceException;
import com.example.mallsystem1104.service.FileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author zy
 * @Date 2024/12/10 17:18
 * @packageName:com.example.mallsystem1104.controller
 * @ClassName:FileController
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Resource
    private FileService fileService;

    @GetMapping("/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response){
        fileService.download(fileName,response);
    }
    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file){
        String url=fileService.upload(file);
        return Result.success(url);
    }

    @DeleteMapping("/{id}")
    @Authority(AuthorityType.requireAuthority)
    public Result deleteById(@PathVariable int id){
        int i=fileService.deleteById(id);
        if(i==1){
            return Result.success();
        }else {
            throw new ServiceException(Constants.CODE_500,"删除失败");
        }
    }

    @PostMapping("/del/batch")
    @Authority(AuthorityType.requireAuthority)
    public Result deleteBatch(@RequestBody List<Integer> ids){
        for(Integer id:ids){
            int i=fileService.deleteById(id);
            if(i!=1){
                throw new ServiceException(Constants.CODE_500,"删除"+fileService.getById(id).getName()+"失败，删除操作已终止");
            }
        }
        return Result.success();
    }

    @GetMapping("/page")
    public Result selectPage(
            @RequestParam int pageNum,
            @RequestParam int pageSize,
            @RequestParam (required = false)String fileName
    ){
        IPage<MyFile> myFileIPage=fileService.selectPage(pageNum,pageSize,fileName);
        return Result.success(myFileIPage);
    }
}
